﻿using System.Linq;
using System.Web;
using System.Web.Mvc;
using Sklep.Domain.Abstract;
using Sklep.Domain.Entities;

namespace Sklep.WebUI.Controllers
{
    [Authorize]
    public class AdminController : Controller
    {
        private readonly IProductRepository _repository;

        public AdminController(IProductRepository repository)
        {
            _repository = repository;
        }

        public ViewResult Index()
        {
            return View(_repository.Products);
        }

        public ViewResult Edit(int productID)
        {
            Product product = _repository.Products.FirstOrDefault(p => p.ProductID == productID);
            return View(product);
        }

        [HttpPost]
        public ActionResult Edit(Product product, HttpPostedFileBase image)
        {
            if (ModelState.IsValid)
            {
                if(image != null)
                {
                    product.ImageMimeType = image.ContentType;
                    product.ImageData = new byte[image.ContentLength];
                    image.InputStream.Read(product.ImageData, 0, image.ContentLength);
                }
                _repository.SaveProduct(product);
                TempData["message"] = string.Format("Zapisano {0}", product.Name);
                return RedirectToAction("Index");
            }
            return View(product);
        }

        public ViewResult Create()
        {
            return View("Edit", new Product());
        }


        [HttpPost]
        public ActionResult Delete(int productID)
        {
            Product product = _repository.Products.FirstOrDefault(p => p.ProductID == productID);
            if(product != null)
            {
                _repository.DeleteProduct(product);
                TempData["message"] = string.Format("Usunięto {0}", product.Name);
            }

            return RedirectToAction("Index");
        }
    }
}
